using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Collections.Concurrent;
using System.Threading;
using System.Linq;

namespace MT5Trade.Models
{
    /// <summary>
    /// 智能重试策略类
    /// 实现指数退避算法，提供科学的重试机制
    /// 核心算法：delay = base_delay × (backoff_factor^attempt) × (1 + random_jitter)
    /// </summary>
    public class RetryStrategy
    {
        #region 常量定义

        // 默认配置参数
        private const int DEFAULT_BASE_DELAY_MS = 100;        // 默认基础延迟100ms
        private const double DEFAULT_BACKOFF_FACTOR = 2.0;    // 默认退避因子2.0
        private const int DEFAULT_MAX_ATTEMPTS = 5;           // 默认最大重试次数5次
        private const int DEFAULT_MAX_DELAY_MS = 30000;       // 默认最大延迟30秒
        private const double DEFAULT_JITTER_FACTOR = 0.1;     // 默认抖动因子10%

        // 系统负载阈值
        private const double HIGH_LOAD_THRESHOLD = 0.8;       // 高负载阈值80%
        private const double CRITICAL_LOAD_THRESHOLD = 0.95;  // 关键负载阈值95%

        // 统计常量
        private const int STATISTICS_WINDOW_SIZE = 1000;      // 统计窗口大小

        #endregion

        #region 字段和属性

        private readonly int _baseDelayMs;
        private readonly double _backoffFactor;
        private readonly int _maxAttempts;
        private readonly int _maxDelayMs;
        private readonly double _jitterFactor;
        private readonly IRandomProvider _randomProvider;
        
        // 统计数据
        private readonly ConcurrentQueue<RetryAttempt> _attemptHistory;
        private readonly ConcurrentDictionary<string, RetryStatistics> _operationStats;
        
        // 泊松重试计算器
        private readonly PoissonRetryCalculator _poissonCalculator;
        private readonly bool _enablePoissonRetry;
        
        // 系统状态监控
        private double _systemLoad;
        private volatile bool _circuitBreakerOpen;
        private DateTime _circuitBreakerOpenTime;
        private readonly object _circuitBreakerLock = new object();
        private readonly object _systemLoadLock = new object();

        /// <summary>
        /// 当前系统负载（0.0-1.0）
        /// </summary>
        public double SystemLoad 
        { 
            get 
            {
                lock (_systemLoadLock)
                {
                    return _systemLoad;
                }
            }
            set 
            {
                lock (_systemLoadLock)
                {
                    _systemLoad = Math.Max(0.0, Math.Min(1.0, value));
                }
            }
        }

        /// <summary>
        /// 熔断器是否开启
        /// </summary>
        public bool CircuitBreakerOpen => _circuitBreakerOpen;

        /// <summary>
        /// 基础延迟时间（毫秒）
        /// </summary>
        public int BaseDelayMs => _baseDelayMs;

        /// <summary>
        /// 退避因子
        /// </summary>
        public double BackoffFactor => _backoffFactor;

        /// <summary>
        /// 最大重试次数
        /// </summary>
        public int MaxAttempts => _maxAttempts;

        /// <summary>
        /// 最大延迟时间（毫秒）
        /// </summary>
        public int MaxDelayMs => _maxDelayMs;

        #endregion

        #region 构造函数

        /// <summary>
        /// 使用默认参数创建重试策略
        /// </summary>
        public RetryStrategy() : this(
            DEFAULT_BASE_DELAY_MS,
            DEFAULT_BACKOFF_FACTOR, 
            DEFAULT_MAX_ATTEMPTS,
            DEFAULT_MAX_DELAY_MS,
            DEFAULT_JITTER_FACTOR,
            enablePoissonRetry: true)
        {
        }

        /// <summary>
        /// 创建自定义重试策略
        /// </summary>
        /// <param name="baseDelayMs">基础延迟时间（毫秒）</param>
        /// <param name="backoffFactor">退避因子（建议1.5-3.0）</param>
        /// <param name="maxAttempts">最大重试次数</param>
        /// <param name="maxDelayMs">最大延迟时间（毫秒）</param>
        /// <param name="jitterFactor">随机抖动因子（0.0-1.0）</param>
        /// <param name="enablePoissonRetry">是否启用泊松过程重试优化</param>
        /// <param name="poissonLambda">泊松参数λ（当启用泊松重试时有效）</param>
        public RetryStrategy(int baseDelayMs, double backoffFactor, int maxAttempts, 
                           int maxDelayMs, double jitterFactor, bool enablePoissonRetry = true, double poissonLambda = 2.0)
        {
            // 参数验证
            if (baseDelayMs <= 0)
                throw new ArgumentException("基础延迟必须大于0", nameof(baseDelayMs));
            if (backoffFactor <= 1.0)
                throw new ArgumentException("退避因子必须大于1.0", nameof(backoffFactor));
            if (maxAttempts <= 0)
                throw new ArgumentException("最大重试次数必须大于0", nameof(maxAttempts));
            if (maxDelayMs <= baseDelayMs)
                throw new ArgumentException("最大延迟必须大于基础延迟", nameof(maxDelayMs));
            if (jitterFactor < 0.0 || jitterFactor > 1.0)
                throw new ArgumentException("抖动因子必须在0.0-1.0范围内", nameof(jitterFactor));

            _baseDelayMs = baseDelayMs;
            _backoffFactor = backoffFactor;
            _maxAttempts = maxAttempts;
            _maxDelayMs = maxDelayMs;
            _jitterFactor = jitterFactor;
            
            // 使用确定性随机数生成器
            _randomProvider = DeterministicRandomProvider.CreateForOptimization($"RetryStrategy_{DateTime.Today:yyyyMMdd}");
            _attemptHistory = new ConcurrentQueue<RetryAttempt>();
            _operationStats = new ConcurrentDictionary<string, RetryStatistics>();
            
            // 初始化泊松重试计算器
            _enablePoissonRetry = enablePoissonRetry;
            if (_enablePoissonRetry)
            {
                _poissonCalculator = new PoissonRetryCalculator(
                    initialLambda: poissonLambda,
                    attemptCost: 1.0,
                    timeCost: 0.01,
                    failureCost: 100.0
                );
            }
            
            _systemLoad = 0.0;
            _circuitBreakerOpen = false;
        }

        #endregion

        #region 核心重试方法

        /// <summary>
        /// 异步重试执行
        /// </summary>
        /// <typeparam name="T">返回类型</typeparam>
        /// <param name="operation">要执行的操作</param>
        /// <param name="operationName">操作名称（用于统计）</param>
        /// <param name="shouldRetry">自定义重试条件判断</param>
        /// <returns>操作结果</returns>
        public async Task<T> ExecuteAsync<T>(Func<Task<T>> operation, 
                                           string operationName = "DefaultOperation",
                                           Func<Exception, bool> shouldRetry = null)
        {
            if (operation == null)
                throw new ArgumentNullException(nameof(operation));

            // 检查熔断器状态
            if (_circuitBreakerOpen && !ShouldAttemptCircuitBreakerRecovery())
            {
                throw new InvalidOperationException("熔断器开启，拒绝执行操作");
            }

            var context = new RetryContext
            {
                OperationName = operationName,
                StartTime = DateTime.UtcNow,
                AttemptNumber = 0
            };

            Exception lastException = null;
            
            for (int attempt = 1; attempt <= _maxAttempts; attempt++)
            {
                context.AttemptNumber = attempt;
                
                try
                {
                    // 执行操作
                    var result = await operation();
                    
                    // 记录成功
                    RecordAttempt(context, null, true);
                    UpdateOperationStatistics(operationName, true, attempt, DateTime.UtcNow - context.StartTime);
                    
                    // 如果成功且熔断器开启，尝试关闭熔断器
                    if (_circuitBreakerOpen)
                    {
                        TryCloseCircuitBreaker();
                    }
                    
                    return result;
                }
                catch (Exception ex)
                {
                    lastException = ex;
                    
                    // 判断是否应该重试
                    if (!ShouldRetryException(ex, shouldRetry) || attempt >= _maxAttempts)
                    {
                        // 记录失败
                        RecordAttempt(context, ex, false);
                        UpdateOperationStatistics(operationName, false, attempt, DateTime.UtcNow - context.StartTime);
                        
                        // 检查是否需要开启熔断器
                        CheckCircuitBreakerCondition(operationName);
                        
                        throw;
                    }
                    
                    // 记录重试尝试
                    RecordAttempt(context, ex, false);
                    
                    // 计算延迟时间
                    var delayMs = CalculateDelay(attempt);
                    
                    // 等待延迟
                    await Task.Delay(delayMs);
                }
            }

            // 记录最终失败
            UpdateOperationStatistics(operationName, false, _maxAttempts, DateTime.UtcNow - context.StartTime);
            CheckCircuitBreakerCondition(operationName);
            
            throw lastException ?? new InvalidOperationException("重试次数已用完");
        }

        /// <summary>
        /// 同步重试执行
        /// </summary>
        /// <typeparam name="T">返回类型</typeparam>
        /// <param name="operation">要执行的操作</param>
        /// <param name="operationName">操作名称（用于统计）</param>
        /// <param name="shouldRetry">自定义重试条件判断</param>
        /// <returns>操作结果</returns>
        public T Execute<T>(Func<T> operation, 
                           string operationName = "DefaultOperation",
                           Func<Exception, bool> shouldRetry = null)
        {
            return ExecuteAsync(() => Task.FromResult(operation()), operationName, shouldRetry).Result;
        }

        /// <summary>
        /// 异步重试执行（无返回值）
        /// </summary>
        /// <param name="operation">要执行的操作</param>
        /// <param name="operationName">操作名称（用于统计）</param>
        /// <param name="shouldRetry">自定义重试条件判断</param>
        public async Task ExecuteAsync(Func<Task> operation, 
                                     string operationName = "DefaultOperation",
                                     Func<Exception, bool> shouldRetry = null)
        {
            await ExecuteAsync(async () =>
            {
                await operation();
                return true;
            }, operationName, shouldRetry);
        }

        #endregion

        #region 延迟计算

        /// <summary>
        /// 计算重试延迟时间
        /// 使用指数退避算法：delay = base_delay × (backoff_factor^attempt) × (1 + random_jitter)
        /// 考虑系统负载动态调整
        /// </summary>
        /// <param name="attempt">重试次数</param>
        /// <returns>延迟时间（毫秒）</returns>
        public int CalculateDelay(int attempt)
        {
            if (attempt <= 0)
                return 0;

            // 基础指数退避计算
            double baseDelay = _baseDelayMs * Math.Pow(_backoffFactor, attempt - 1);
            
            // 添加随机抖动（±jitterFactor范围内）
            double jitter = (_randomProvider.NextDouble() - 0.5) * 2 * _jitterFactor;
            double delayWithJitter = baseDelay * (1 + jitter);
            
            // 根据系统负载调整延迟
            double loadMultiplier = CalculateLoadMultiplier();
            double adjustedDelay = delayWithJitter * loadMultiplier;
            
            // 限制在最大延迟范围内
            int finalDelay = (int)Math.Min(adjustedDelay, _maxDelayMs);
            
            return Math.Max(finalDelay, 1); // 确保至少1ms延迟
        }

        /// <summary>
        /// 根据系统负载计算延迟倍数
        /// </summary>
        /// <returns>负载调整倍数</returns>
        private double CalculateLoadMultiplier()
        {
            double currentLoad = SystemLoad; // 读取一次，避免多次锁定
            
            if (currentLoad <= HIGH_LOAD_THRESHOLD)
            {
                // 低负载：正常延迟
                return 1.0;
            }
            else if (currentLoad <= CRITICAL_LOAD_THRESHOLD)
            {
                // 高负载：增加延迟
                double loadFactor = (currentLoad - HIGH_LOAD_THRESHOLD) / (CRITICAL_LOAD_THRESHOLD - HIGH_LOAD_THRESHOLD);
                return 1.0 + loadFactor * 2.0; // 最多增加200%
            }
            else
            {
                // 临界负载：大幅增加延迟
                return 3.0;
            }
        }

        #endregion

        #region 泊松重试方法

        /// <summary>
        /// 基于泊松过程的智能异步重试执行
        /// </summary>
        /// <typeparam name="T">返回类型</typeparam>
        /// <param name="operation">要执行的操作</param>
        /// <param name="operationName">操作名称（用于统计）</param>
        /// <param name="currentVolatility">当前市场波动率</param>
        /// <param name="shouldRetry">自定义重试条件判断</param>
        /// <returns>操作结果</returns>
        public async Task<T> ExecuteWithPoissonRetryAsync<T>(Func<Task<T>> operation, 
                                                             string operationName = "DefaultOperation",
                                                             double currentVolatility = 0.5,
                                                             Func<Exception, bool> shouldRetry = null)
        {
            if (operation == null)
                throw new ArgumentNullException(nameof(operation));

            // 如果未启用泊松重试，使用传统方法
            if (!_enablePoissonRetry || _poissonCalculator == null)
            {
                return await ExecuteAsync(operation, operationName, shouldRetry);
            }

            // 检查熔断器状态
            if (_circuitBreakerOpen && !ShouldAttemptCircuitBreakerRecovery())
            {
                throw new InvalidOperationException("熔断器开启，拒绝执行操作");
            }

            // 获取泊松重试策略
            var strategy = _poissonCalculator.CalculateOptimalStrategy(operationName, currentVolatility, SystemLoad);
            
            var context = new RetryContext
            {
                OperationName = operationName,
                StartTime = DateTime.UtcNow,
                AttemptNumber = 0
            };

            Exception lastException = null;
            
            for (int attempt = 1; attempt <= strategy.OptimalRetryCount; attempt++)
            {
                context.AttemptNumber = attempt;
                
                try
                {
                    // 执行操作
                    var result = await operation();
                    
                    // 记录成功到泊松计算器
                    _poissonCalculator.RecordAttemptResult(operationName, attempt, true, 
                        (long)(DateTime.UtcNow - context.StartTime).TotalMilliseconds);
                    
                    // 记录到传统统计系统
                    RecordAttempt(context, null, true);
                    UpdateOperationStatistics(operationName, true, attempt, DateTime.UtcNow - context.StartTime);
                    
                    // 如果成功且熔断器开启，尝试关闭熔断器
                    if (_circuitBreakerOpen)
                    {
                        TryCloseCircuitBreaker();
                    }
                    
                    return result;
                }
                catch (Exception ex)
                {
                    lastException = ex;
                    
                    // 判断是否应该重试
                    if (!ShouldRetryException(ex, shouldRetry) || attempt >= strategy.OptimalRetryCount)
                    {
                        // 记录失败到泊松计算器
                        _poissonCalculator.RecordAttemptResult(operationName, attempt, false, 
                            (long)(DateTime.UtcNow - context.StartTime).TotalMilliseconds);
                        
                        // 记录到传统统计系统
                        RecordAttempt(context, ex, false);
                        UpdateOperationStatistics(operationName, false, attempt, DateTime.UtcNow - context.StartTime);
                        
                        // 检查是否需要开启熔断器
                        CheckCircuitBreakerCondition(operationName);
                        
                        throw;
                    }
                    
                    // 使用泊松策略计算的间隔进行延迟
                    if (attempt <= strategy.RetryIntervals.Length)
                    {
                        int delay = strategy.RetryIntervals[attempt - 1];
                        await Task.Delay(delay);
                    }
                    else
                    {
                        // 备用延迟计算
                        await Task.Delay(CalculateDelay(attempt));
                    }
                }
            }

            // 不应该到达这里
            throw lastException ?? new InvalidOperationException("重试逻辑出现异常");
        }

        /// <summary>
        /// 获取泊松重试计算器的当前状态报告
        /// </summary>
        /// <returns>泊松重试报告，如果未启用则返回null</returns>
        public PoissonRetryReport GetPoissonRetryReport()
        {
            return _enablePoissonRetry ? _poissonCalculator?.GenerateReport() : null;
        }

        /// <summary>
        /// 预测指定操作的最优重试策略
        /// </summary>
        /// <param name="operationType">操作类型</param>
        /// <param name="currentVolatility">当前市场波动率</param>
        /// <returns>预测的最优重试策略，如果未启用则返回null</returns>
        public PoissonRetryStrategy PredictOptimalStrategy(string operationType, double currentVolatility = 0.5)
        {
            return _enablePoissonRetry ? _poissonCalculator?.CalculateOptimalStrategy(operationType, currentVolatility, SystemLoad) : null;
        }

        /// <summary>
        /// 是否启用了泊松重试优化
        /// </summary>
        public bool IsPoissonRetryEnabled => _enablePoissonRetry;

        /// <summary>
        /// 当前泊松参数λ值
        /// </summary>
        public double CurrentLambda => _enablePoissonRetry ? _poissonCalculator?.Lambda ?? 0.0 : 0.0;

        #endregion

        #region 重试条件判断

        /// <summary>
        /// 判断异常是否应该重试
        /// </summary>
        /// <param name="exception">发生的异常</param>
        /// <param name="customShouldRetry">自定义重试条件</param>
        /// <returns>是否应该重试</returns>
        private bool ShouldRetryException(Exception exception, Func<Exception, bool> customShouldRetry)
        {
            // 首先检查自定义重试条件
            if (customShouldRetry != null)
            {
                return customShouldRetry(exception);
            }

            // 默认重试条件判断
            return exception switch
            {
                // 网络相关异常 - 重试
                System.Net.Http.HttpRequestException _ => true,
                System.Net.Sockets.SocketException _ => true,
                TimeoutException _ => true,
                TaskCanceledException _ => true,
                
                // 数据库临时异常 - 重试  
                // Microsoft.Data.SqlClient.SqlException sqlEx when IsTransientSqlError(sqlEx.Number) => true,
                
                // 参数错误 - 不重试
                ArgumentNullException _ => false,
                ArgumentException _ => false,
                
                // 安全异常 - 不重试
                UnauthorizedAccessException _ => false,
                System.Security.SecurityException _ => false,
                
                // 其他异常 - 默认重试
                _ => true
            };
        }

        /// <summary>
        /// 判断SQL异常是否为临时性错误
        /// </summary>
        /// <param name="errorNumber">SQL错误号</param>
        /// <returns>是否为临时性错误</returns>
        private static bool IsTransientSqlError(int errorNumber)
        {
            // SQL Server临时性错误代码
            return errorNumber switch
            {
                -2 => true,      // 超时
                2 => true,       // 超时
                53 => true,      // 网络路径未找到
                121 => true,     // 信号量超时
                1205 => true,    // 死锁
                1222 => true,    // 锁请求超时
                8645 => true,    // 内存不足
                8651 => true,    // 内存不足
                _ => false
            };
        }

        #endregion

        #region 熔断器机制

        /// <summary>
        /// 检查是否需要开启熔断器
        /// </summary>
        /// <param name="operationName">操作名称</param>
        private void CheckCircuitBreakerCondition(string operationName)
        {
            if (_circuitBreakerOpen)
                return;

            lock (_circuitBreakerLock)
            {
                if (_circuitBreakerOpen)
                    return;

                var stats = GetOperationStatistics(operationName);
                
                // 熔断器开启条件：
                // 1. 最近10次尝试中失败率超过80%
                // 2. 或者系统负载超过95%
                                 if ((stats.RecentFailureRate > 0.8 && stats.RecentAttemptCount >= 10) ||
                     SystemLoad > CRITICAL_LOAD_THRESHOLD)
                {
                    _circuitBreakerOpen = true;
                    _circuitBreakerOpenTime = DateTime.UtcNow;
                    
                                         Console.WriteLine($"[RetryStrategy] 熔断器开启 - 操作: {operationName}, " +
                                     $"失败率: {stats.RecentFailureRate:P2}, " +
                                     $"系统负载: {SystemLoad:P2}");
                }
            }
        }

        /// <summary>
        /// 判断是否应该尝试恢复熔断器
        /// </summary>
        /// <returns>是否可以尝试</returns>
        private bool ShouldAttemptCircuitBreakerRecovery()
        {
            // 熔断器开启30秒后允许尝试恢复
            return DateTime.UtcNow - _circuitBreakerOpenTime > TimeSpan.FromSeconds(30);
        }

        /// <summary>
        /// 尝试关闭熔断器
        /// </summary>
        private void TryCloseCircuitBreaker()
        {
            lock (_circuitBreakerLock)
            {
                                 if (_circuitBreakerOpen && SystemLoad < HIGH_LOAD_THRESHOLD)
                {
                    _circuitBreakerOpen = false;
                    Console.WriteLine("[RetryStrategy] 熔断器关闭 - 系统恢复正常");
                }
            }
        }

        #endregion

        #region 统计和监控

        /// <summary>
        /// 记录重试尝试
        /// </summary>
        /// <param name="context">重试上下文</param>
        /// <param name="exception">发生的异常（如果有）</param>
        /// <param name="isSuccess">是否成功</param>
        private void RecordAttempt(RetryContext context, Exception exception, bool isSuccess)
        {
            var attempt = new RetryAttempt
            {
                OperationName = context.OperationName,
                AttemptNumber = context.AttemptNumber,
                Timestamp = DateTime.UtcNow,
                IsSuccess = isSuccess,
                Exception = exception,
                SystemLoad = this.SystemLoad
            };

            _attemptHistory.Enqueue(attempt);
            
            // 保持统计窗口大小
            while (_attemptHistory.Count > STATISTICS_WINDOW_SIZE)
            {
                _attemptHistory.TryDequeue(out _);
            }
        }

        /// <summary>
        /// 更新操作统计
        /// </summary>
        /// <param name="operationName">操作名称</param>
        /// <param name="isSuccess">是否成功</param>
        /// <param name="attemptCount">尝试次数</param>
        /// <param name="duration">执行时长</param>
        private void UpdateOperationStatistics(string operationName, bool isSuccess, int attemptCount, TimeSpan duration)
        {
            _operationStats.AddOrUpdate(operationName,
                new RetryStatistics(operationName),
                (key, existingStats) =>
                {
                    existingStats.RecordAttempt(isSuccess, attemptCount, duration);
                    return existingStats;
                });
        }

        /// <summary>
        /// 获取操作统计信息
        /// </summary>
        /// <param name="operationName">操作名称</param>
        /// <returns>统计信息</returns>
        public RetryStatistics GetOperationStatistics(string operationName)
        {
            return _operationStats.GetValueOrDefault(operationName, new RetryStatistics(operationName));
        }

        /// <summary>
        /// 获取所有操作的统计信息
        /// </summary>
        /// <returns>所有统计信息</returns>
        public Dictionary<string, RetryStatistics> GetAllStatistics()
        {
            return new Dictionary<string, RetryStatistics>(_operationStats);
        }

        /// <summary>
        /// 获取系统状态报告
        /// </summary>
        /// <returns>状态报告</returns>
        public RetrySystemStatus GetSystemStatus()
        {
            var recentAttempts = _attemptHistory.Where(a => a.Timestamp > DateTime.UtcNow.AddMinutes(-5)).ToList();
            
            return new RetrySystemStatus
            {
                SystemLoad = this.SystemLoad,
                CircuitBreakerOpen = _circuitBreakerOpen,
                CircuitBreakerOpenTime = _circuitBreakerOpenTime,
                RecentAttemptCount = recentAttempts.Count,
                RecentSuccessRate = recentAttempts.Any() ? 
                    recentAttempts.Count(a => a.IsSuccess) / (double)recentAttempts.Count : 0.0,
                OperationCount = _operationStats.Count,
                TotalAttemptCount = _attemptHistory.Count
            };
        }

        /// <summary>
        /// 重置所有统计数据
        /// </summary>
        public void ResetStatistics()
        {
            while (_attemptHistory.TryDequeue(out _)) { }
            _operationStats.Clear();
        }

        #endregion
    }

    #region 相关数据类

    /// <summary>
    /// 重试上下文信息
    /// </summary>
    internal class RetryContext
    {
        public string OperationName { get; set; }
        public DateTime StartTime { get; set; }
        public int AttemptNumber { get; set; }
    }

    /// <summary>
    /// 重试尝试记录
    /// </summary>
    public class RetryAttempt
    {
        public string OperationName { get; set; }
        public int AttemptNumber { get; set; }
        public DateTime Timestamp { get; set; }
        public bool IsSuccess { get; set; }
        public Exception Exception { get; set; }
        public double SystemLoad { get; set; }
    }

    /// <summary>
    /// 操作统计信息
    /// </summary>
    public class RetryStatistics
    {
        private readonly object _lock = new object();
        private readonly Queue<bool> _recentResults = new Queue<bool>();
        private const int RECENT_WINDOW_SIZE = 20;

        public string OperationName { get; }
        public int TotalAttempts { get; private set; }
        public int SuccessfulAttempts { get; private set; }
        public int FailedAttempts => TotalAttempts - SuccessfulAttempts;
        public double SuccessRate => TotalAttempts == 0 ? 0.0 : SuccessfulAttempts / (double)TotalAttempts;
        public double RecentFailureRate { get; private set; }
        public int RecentAttemptCount => _recentResults.Count;
        public double AverageAttemptCount { get; private set; }
        public TimeSpan AverageDuration { get; private set; }
        public DateTime LastAttemptTime { get; private set; }

        public RetryStatistics(string operationName)
        {
            OperationName = operationName;
        }

        /// <summary>
        /// 记录重试尝试
        /// </summary>
        /// <param name="isSuccess">是否成功</param>
        /// <param name="attemptCount">尝试次数</param>
        /// <param name="duration">执行时长</param>
        public void RecordAttempt(bool isSuccess, int attemptCount, TimeSpan duration)
        {
            lock (_lock)
            {
                TotalAttempts++;
                if (isSuccess)
                    SuccessfulAttempts++;

                // 更新平均尝试次数
                AverageAttemptCount = (AverageAttemptCount * (TotalAttempts - 1) + attemptCount) / TotalAttempts;
                
                // 更新平均执行时长
                var totalTicks = AverageDuration.Ticks * (TotalAttempts - 1) + duration.Ticks;
                AverageDuration = new TimeSpan(totalTicks / TotalAttempts);
                
                LastAttemptTime = DateTime.UtcNow;

                // 更新最近结果窗口
                _recentResults.Enqueue(isSuccess);
                while (_recentResults.Count > RECENT_WINDOW_SIZE)
                {
                    _recentResults.Dequeue();
                }

                // 计算最近失败率
                var recentFailures = _recentResults.Count(r => !r);
                RecentFailureRate = _recentResults.Count == 0 ? 0.0 : recentFailures / (double)_recentResults.Count;
            }
        }
    }

    /// <summary>
    /// 重试系统状态
    /// </summary>
    public class RetrySystemStatus
    {
        public double SystemLoad { get; set; }
        public bool CircuitBreakerOpen { get; set; }
        public DateTime CircuitBreakerOpenTime { get; set; }
        public int RecentAttemptCount { get; set; }
        public double RecentSuccessRate { get; set; }
        public int OperationCount { get; set; }
        public int TotalAttemptCount { get; set; }
        
        /// <summary>
        /// 获取系统健康状态描述
        /// </summary>
        public string GetHealthStatus()
        {
            if (CircuitBreakerOpen)
                return "熔断器开启 - 系统保护中";
            
            if (SystemLoad > 0.95)
                return "系统负载过高 - 需要关注";
            
            if (RecentSuccessRate < 0.8 && RecentAttemptCount > 10)
                return "成功率较低 - 需要调查";
                
            return "系统运行正常";
        }
    }

    #endregion
}
